from django.shortcuts import render
from django.shortcuts import render_to_response  
from django.template import RequestContext
from django.http import HttpResponse,Http404,HttpResponseRedirect
from django.views import View
from django.core.exceptions import PermissionDenied
from my_learn.models import userInfo
from django.db import connection
import json
import math
from my_learn.xtinf import xt

# Create your views here.
#Bootstrap 测试
def login(request):
    return render(request,'login.html')
def index(request):
    context= {}
    test=my_test()
    ip = test.get_client_ip(request)
    tablename = "my_learn_userinfo"
    # header = test.getColumnByTableName(tablename)
    # alluser = userInfo.objects.all()
    usercount = test.get_source_count_by_tablename(tablename)
    username = request.COOKIES["username"]
    pagetotal = 10
    count = math.ceil(usercount / pagetotal)
    total = range(1, count + 1)
    # data = test.pagination(tablename, header, pagetotal, 0)
    total=range(1,count+1)
    username=request.GET.get("username")
    xt_1 = xt()
    # data_1 = xt_1.getXTInf()
    data_1=dict(
        username=username,
        usercount="111"
        )
    header = []
    data = []
    for k,v in data_1.items():
        header.append(k)
        data.append(v)
    context = dict(
        username=username,
        data=data,
        header=header,
        total=total,
        count=count,
        curpage=1,
        pagetotal=pagetotal,
        tableTitle=tablename,
        ip=ip,
        colnum=len(header),
    )
    return render(request,'index.html',context)
def home(request):
    return render(request,"linux.html")
class my_test(View):
    def post(self, request, *args, **kwargs):
        #获取要对用户进行什么操作
        slug = self.kwargs.get('slug')
        if hasattr(self,slug):
            func = getattr(self,slug)
            return func(request)
        else:
            return Http404
        # if slug == "checklogin":
        #     return self.checklogin(request)
        raise PermissionDenied
    def get(self,request,*args, **kwargs):
        #如果是get请求直接返回404页面
        slug = self.kwargs.get('slug')
        if hasattr(self,slug):
            func = getattr(self,slug)
            return func(request)
        else:
            return Http404
    def checklogin(self,request):
        username=request.POST.get("username")
        password=request.POST.get("password")
        result={}
        isLogin=False
        try:
            result_sql=userInfo.objects.filter(acount=username,password=password)#模型根据条件查询数据
            if(result_sql.count()>0):
                isLogin=True
        except:
            result.setdefault("isLogin", isLogin)
            result.setdefault("msg", "数据库连接失败")
            return HttpResponse(json.dumps(result), content_type="application/json")
        if isLogin:
            result.setdefault("isLogin",isLogin)
            return HttpResponse(json.dumps(result),content_type="application/json")
        else:
            result.setdefault("isLogin",isLogin)
            result.setdefault("msg","用户名或密码错误")
            return HttpResponse(json.dumps(result),content_type="application/json")
    def testpage(self,request):
        ip=self.get_client_ip(request)
        tablename="my_learn_userinfo"
        header=self.getColumnByTableName(tablename)
        # alluser = userInfo.objects.all()
        usercount=self.get_source_count_by_tablename(tablename)
        username = request.COOKIES["username"]
        try:
            page=int(request.POST.get("curpage"))
            pagetotal = int(request.POST.get("pagetotal"))
        except:
            page=1
            pagetotal=10
        count = math.ceil(usercount / pagetotal)
        total = range(1,count + 1)
        source_num_start=(page-1)*pagetotal
        data=self.pagination(tablename,header,pagetotal,source_num_start)
        # for i in range((page-1)*pagetotal,page*pagetotal):#加载当前页用户信息
        #     if i<alluser.count():
        #         for info in header:
        #             user.append(getattr(alluser[i], info))  # 遍历用户信息
        #         else:
        #             data.append(user)
        #             user = []
        #     else:
        #         break
        context=dict(
            username=username,
            data=data,
            header=header,
            total=total,
            count=count,
            curpage=page,
            pagetotal=pagetotal,
            tableTitle=tablename,
            ip=ip,
            colnum=len(header),
        )
        return render(request,'dataTable.html',context)
        # return HttpResponse(json.dumps(context),content_type="application/json")

    def get_client_ip(self,request):
        try:
            real_ip = request.META['HTTP_X_FORWARDED_FOR']
            regip = real_ip.split(",")[0]
        except:
            try:
                regip = request.META['REMOTE_ADDR']
            except:
                regip = ""
        return regip

    def getColumnByTableName(self,tablename):
        sql = "PRAGMA table_info([%s])" % tablename
        cursor = connection.cursor()
        ex_result = cursor.execute(sql)
        result = []
        for column in ex_result:
           result.append(column[1])
        return result
    def get_source_count_by_tablename(self,tablename):
        sql="select count (*) as num from %s" % tablename
        result=connection.cursor().execute(sql)
        for i in result:
            num=i[0]
        return num
    def getresult(self,request):
        cmdtext=request.POST.get("cmdtext")
        xtlx=request.POST.get("xtlx")
        result={}
        xt_1=xt()
        b=xt_1.getresult(cmdtext,xtlx)
        result.setdefault("result", str(b))
        return HttpResponse(json.dumps(result), content_type="application/json")
    def pagination(self,tablename,header,page_source_count,source_num_start):
        sql="SELECT * FROM %(tablename)s order by %(colname)s limit %(page_source_count)s offset %(source_num_start)s" % dict(
            tablename=tablename,
            colname=header[0],
            page_source_count=page_source_count,
            source_num_start=source_num_start,
        )
        result = connection.cursor().execute(sql) #得到查询结果
        return result
class my_home(View):
    def post(self, request, *args, **kwargs):
        #获取要对用户进行什么操作
        slug = self.kwargs.get('slug')
        if hasattr(self,slug):
            func = getattr(self,slug)
            return func(request)
        else:
            return Http404
        # if slug == "checklogin":
        #     return self.checklogin(request)
        raise PermissionDenied
    def get(self,request,*args, **kwargs):
        #如果是get请求直接返回404页面
        slug = self.kwargs.get('slug')
        if hasattr(self,slug):
            func = getattr(self,slug)
            return func(request)
        else:
            return Http404